package v3

import (
	"context"
	"encoding/json"
	"github.com/go-pay/gopay"
	"go.uber.org/zap"
)

// alipay.open.iotmbs.isvdevice.bind(绑定设备)
//	文档地址：https://opendocs.alipay.com/pre-apis/06y0jq
func (c *ClientV3) IotDeviceBind(ctx context.Context, bm gopay.BodyMap) (*PayData, error) {

	err := bm.CheckEmptyError("sn", "project_id", "device_category", "scene_type")
	if err != nil {
		return nil, err
	}

	authString := c.GenAuthString()
	content := c.GenContent(authString, "POST", AlipayIotDeviceBindUrl, bm.JsonBody(), "")
	sign, err := c.MakeSign(content, "RSA2")
	authorization := c.GentAuthorization("ALIPAY-SHA256withRSA", authString, sign)
	if err != nil {
		return nil, err
	}

	url := AlipayBaseUrl + AlipayIotDeviceBindUrl
	headers := make(map[string]string)
	headers["authorization"] = authorization
	headers["Content-Type"] = "application/json;charset=utf-8"
	bs, headerResp, err := c.Post(url, headers, bm)

	// 验签
	if headerResp != nil {
		headerMap := make(map[string]string)
		headerMap["aliapy-signature"] = headerResp.Get("aliapy-signature")
		headerMap["alipay-sn"] = headerResp.Get("alipay-sn")
		headerMap["alipay-timestamp"] = headerResp.Get("alipay-timestamp")
		headerMap["alipay-nonce"] = headerResp.Get("alipay-nonce")
		body := bs.ToJson()
		err := c.VerifySign(headerMap, body)
		if err != nil {
			b, _ := json.Marshal(headerMap)
			zap.L().Error("verify sign error：" + err.Error() + "|" + string(b) + "|" + body)
			return nil, err
		}
	}

	return bs, err
}

// alipay.open.iotmbs.isvdevice.unbind(解绑设备)
//	文档地址：https://opendocs.alipay.com/pre-apis/06xzqy
func (c *ClientV3) IotDeviceUnbind(ctx context.Context, bm gopay.BodyMap) (*PayData, error) {

	err := bm.CheckEmptyError("sn", "project_id")
	if err != nil {
		return nil, err
	}

	authString := c.GenAuthString()
	content := c.GenContent(authString, "POST", AlipayIotDeviceUnBindUrl, bm.JsonBody(), "")
	sign, err := c.MakeSign(content, "RSA2")
	authorization := c.GentAuthorization("ALIPAY-SHA256withRSA", authString, sign)
	if err != nil {
		return nil, err
	}

	url := AlipayBaseUrl + AlipayIotDeviceUnBindUrl
	headers := make(map[string]string)
	headers["authorization"] = authorization
	headers["Content-Type"] = "application/json;charset=utf-8"
	bs, headerResp, err := c.Post(url, headers, bm)

	// 验签
	if headerResp != nil {
		headerMap := make(map[string]string)
		headerMap["aliapy-signature"] = headerResp.Get("aliapy-signature")
		headerMap["alipay-sn"] = headerResp.Get("alipay-sn")
		headerMap["alipay-timestamp"] = headerResp.Get("alipay-timestamp")
		headerMap["alipay-nonce"] = headerResp.Get("alipay-nonce")
		body := bs.ToJson()
		err := c.VerifySign(headerMap, body)
		if err != nil {
			b, _ := json.Marshal(headerMap)
			zap.L().Error("verify sign error：" + err.Error() + "|" + string(b) + "|" + body)
			return nil, err
		}
	}

	return bs, err
}
